#!/usr/bin/python3
"""
Configure the SELinux state on the system.

The stage configures the SELinux state on the system in /etc/selinux/config.
The policy enforcement state and active policy type can be configured.
"""


import sys

import osbuild.api


SCHEMA = """
"additionalProperties": false,
"description": "SELinux state configuration.",
"properties": {
  "state": {
    "type": "string",
    "description": "The active policy enforcement state.",
    "enum": ["enforcing", "permissive", "disabled"]
  },
  "type": {
    "type": "string",
    "description": "The active policy type.",
    "enum": ["targeted", "minimum", "mls"]
  }
}
"""


def main(tree, options):
    state = options.get("state")
    policy_type = options.get("type")

    selinux_config_file = "/etc/selinux/config"
    selinux_state_key = "SELINUX"
    selinux_type_key = "SELINUXTYPE"

    selinux_config_lines = []
    with open(f"{tree}{selinux_config_file}") as f:
        selinux_config_lines = f.readlines()

    for idx, line in enumerate(selinux_config_lines):
        if line.startswith("#") or not line.strip():
            continue

        line_key, _ = line.strip().split("=", 1)

        if line_key == selinux_state_key:
            selinux_config_lines[idx] = f"{selinux_state_key}={state}\n"
        elif line_key == selinux_type_key and policy_type:
            selinux_config_lines[idx] = f"{selinux_type_key}={policy_type}\n"

    with open(f"{tree}{selinux_config_file}", "w") as f:
        f.writelines(selinux_config_lines)

    return 0


if __name__ == '__main__':
    args = osbuild.api.arguments()
    r = main(args["tree"], args["options"])
    sys.exit(r)
